package com.zfy.dao;

import com.zfy.entity.Category;
import com.zfy.utils.DBManager;
import com.zfy.utils.QueryDataResult;

import java.util.ArrayList;
import java.util.List;

public class CategoryDao {

    public List<Category> getCates(String name, Integer page, Integer limit){
        String sql = " SELECT * FROM category WHERE 1=1 ";
        if( name !=null && !name.equals("")) {
            sql += " AND cname LIKE '%"+name+"%' ";
        }
        if( page !=null && limit !=null ) {
            sql += " LIMIT "+(page-1)*limit+","+limit;
        }
        System.out.println(sql);
        QueryDataResult qr = DBManager.executeQuery(sql);
        List<Category> categoryList = new ArrayList<Category>();
        if(qr != null ){
            try{
                while (qr.rs.next()){
                    Category category = new Category(qr.rs.getInt("cid"), qr.rs.getString("cname"));
                    categoryList.add(category);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return categoryList;
    }

    public boolean addCates(Category category) {
        String sql = String.format("insert into category(cname) values('%s')", category.getCname());
        int jg = DBManager.executeUpdate(sql);
        if (jg > 0) {
            return true;
        }else{
            return false;
        }

    }

    public boolean updateCates(Category category) {
        String sql = String.format("update category set cname='%s' where cid=%d", category.getCname(), category.getCid());
        int jg = DBManager.executeUpdate(sql);
        if (jg > 0) {
            return true;
        }else{
            return false;
        }

    }

}
